
/* JavaScript content from js/customer-main.js in folder common */

var passengerWin, driverWin;
var driverLatLng, oldLatLng, setTimeOutFunc, continueTrace = true;
var distance;
var directionsDisplay, directionsService;
var allowOrder = false;
var fromAddrLat, fromAddrLng, toAddrLat, toAddrLng, latlng;
//customer-main.html is a multi-use page, with 3 pages: customer-main (cusmain or custMain), response (response)
//and real-time(realTime). The pages move like this: custMain-->loading-->response-->realTime

//customer-main displays: a map with current position and drivers, with options to call now, or book taxi.

//response displays: a map with current position and the selected driver ONLY, with an option to accept or decline
// It also displays driver information

//realTime (only if customer accepted): a map with current position and selected driver's position, updated in real time
// displays driver information

(function($){
	if(window.page == 0){
		$(".cusmain").removeClass("hidden");
		$(".cusmainheader").removeClass("hidden");
		$(".dispOptions").removeClass("hidden");
		$(".response").addClass("hidden");
		$(".responseheader").addClass("hidden");
		$("#mapContainer").addClass("custMainMap");
		$("#mapContainer").removeClass("responseMap");
		$(".orderTaxi").addClass("hidden");
		$("#noOrderPopup").addClass("hidden");
		
		
	}
	else if(window.page == 1){
		$(".cusmain").addClass("hidden");
		$(".cusmainheader").addClass("hidden");
		$(".dispOptions").addClass("hidden");
		$(".response").removeClass("hidden");
		$(".responseheader").removeClass("hidden");
		$("#mapContainer").removeClass("custMainMap");
		$("#mapContainer").addClass("responseMap");
		$(".orderTaxi").addClass("hidden");
		$("#noOrderPopup").addClass("hidden");
		//initializes the elements required for driver location and information
		setTimeout(function() {
			window.initializeOtherElement(window.map);
		}, 500);
		
	}
	else if(window.page == 2){
		
	}
})(jQuery);

//---------------------------customer-main-----------------------------------

/**
 * function that changes to loading page
 * 
 */
function changeToLoading(){
	window.custOption = $("input:radio[name=options]:checked").val();
	jQuery.mobile.changePage("../view/loading.html");
}

/**
 * changes the function of the bookNowBtn to display a popup
 * that does not allow the person to call again
 */
var switchPopup = function(){
	$("#bookNowBtn").attr("data-rel", "popup");
	$("#bookNowBtn").attr("href", "#noOrderPopup");
	$("#bookNowBtn").off("click", changeToLoading);
};


/**
 * Gives the bookNowBtn function to hail taxis again
 * removes its attributes for displaying the popup
 */
var switchLoading = function(){
	$("#bookNowBtn").removeAttr("data-rel");
	$("#bookNowBtn").removeAttr("href");
	$("#bookNowBtn").on("click", changeToLoading);
};



//sets event handlers for the custMain menu and buttons
$("#backToCusmain").on("click", backToCustmain);

$("#curOrdersLink").on("click", function(){
	jQuery.mobile.changePage("../view/myCurOrders.html");
});

$("#bookNowBtn").on("click", changeToLoading);



$("#orderTaxiBtn").click(changeToOrderTaxi);
$("#microphoto").click(controlRecord);

$("#submitBtn").on("click", submitOrder);
//--------------------------- changeToOrderTaxi ----------------------------------
function changeToOrderTaxi() {
	$(".cusmain").addClass("hidden");
	$(".response").addClass("hidden");
	$(".responseheader").addClass("hidden");
	$("#mapContainer").removeClass("custMainMap");
	$("#mapContainer").addClass("orderTaxiMap");
	$(".orderTaxi").removeClass("hidden");
	$(".cusmainheader").addClass("hidden");
	$("#radioBackground").addClass("hidden");
	$("#submitOrderBtn").on("click", submitOrder);
	initializeAutocomplete();
}

function submitOrder() {
	var setupTimeInput = $('#slider_example_3');
	var fromAddrInput = $('#fromAddr');
	var toAddrInput = $('#toAddr');
	setupTimeInput.change(function() {
		$('#orderInputs div:first-child').css('background-color', 'white');
	});
	
	
	var canSubmit = true;
	if(setupTimeInput.val() == null || setupTimeInput.val() == "") {
		$('#orderInputs div:first-child').css('background-color', '#FFEB00');
		setupTimeInput.attr('placeholder', 'when will you go ?');
		canSubmit = false;
	}
	if(fromAddrLat == null || fromAddrLat == undefined) {
		$('#orderInputs div:nth-child(2)').css('background-color', '#FFEB00');
		fromAddrInput.attr('placeholder', 'where will you set up from ?');
		fromAddrInput.focus(function() {
			$('#orderInputs div:nth-child(2)').css('background-color', 'white');
		});
		canSubmit = false;
	}
	if(toAddrLng == null || toAddrLat == undefined) {
		$('#orderInputs div:nth-child(3)').css('background-color', '#FFEB00');
		toAddrInput.attr('placeholder', 'when will you go ?');
		toAddrInput.focus(function() {
			$('#orderInputs div:nth-child(3)').css('background-color', 'white');
		});
		canSubmit = false;
	}
	if(canSubmit) {
		var invocationData = {
				adapter : 'stAdp',
				procedure : 'orderTaxi',
				parameters : [{'cus_id': window.customer.id,'setupTime':setupTimeInput.val(),'fromAddrLat':fromAddrLat,'fromAddrLng':fromAddrLng, 'toAddrLat': toAddrLat, 'toAddrLng':toAddrLng}]
		};
		busy.show();
		WL.Client.invokeProcedure(invocationData, {
			onSuccess : orderTaxiSuccess,
			onFailure : orderTaxiFailure
		});
	}
	
}

function orderTaxiSuccess() {
	busy.hide();
	alert("order success.");
	backToCustmain();
}

function orderTaxiFailure() {
	busy.hide();
	alert("order failure.");
	backToCustmain();
//	window.showToast("sorry , order failure.");
}

function backToCustmain() {
	window.page=0;
	$(".cusmain").removeClass("hidden");
	$(".cusmainheader").removeClass("hidden");
	$(".dispOptions").removeClass("hidden");
	$(".response").addClass("hidden");
	$(".responseheader").addClass("hidden");
	$("#mapContainer").removeClass("orderTaxiMap");
	$("#mapContainer").addClass("custMainMap");
	$(".orderTaxi").addClass("hidden");
	$("#noOrderPopup").addClass("hidden");
}
function initializeAutocomplete() {
	var fromInput = /** @type {HTMLInputElement} */
	(document.getElementById('fromAddr'));
	var toInput = /** @type {HTMLInputElement} */
	(document.getElementById('toAddr'));
	var fromAutocomplete = new google.maps.places.Autocomplete(fromInput);
	var toAutocomplete = new google.maps.places.Autocomplete(toInput);
	fromAutocomplete.bindTo('bounds', window.map);
	toAutocomplete.bindTo('bounds', window.map);

	var fromInfowindow = new google.maps.InfoWindow();
	var fromMarker = new google.maps.Marker({
		map : window.map
	});
	var toInfowindow = new google.maps.InfoWindow();
	var toMarker = new google.maps.Marker({
		map : window.map
	});
	google.maps.event.addListener(fromAutocomplete, 'place_changed', function() {
		fromInfowindow.close();
	    fromMarker.setVisible(false);
	    var place = fromAutocomplete.getPlace();
	    if (!place.geometry) {
	      return;
	    }
	    // If the place has a geometry, then present it on a map.
	    if (place.geometry.viewport) {
	      window.map.fitBounds(place.geometry.viewport);
	    } else {
	      window.map.setCenter(place.geometry.location);
	      window.map.setZoom(17);  // Why 17? Because it looks good.
	    }
	    fromMarker.setIcon(/** @type {google.maps.Icon} */({
	      url: place.icon,
	      size: new google.maps.Size(71, 71),
	      origin: new google.maps.Point(0, 0),
	      anchor: new google.maps.Point(17, 34),
	      scaledSize: new google.maps.Size(35, 35)
	    }));
	    latlng = place.geometry.location;
	    fromAddrLat = latlng.lat();
	    fromAddrLng = latlng.lng();
	    fromMarker.setPosition(latlng);
	    fromMarker.setVisible(true);
	    var address = '';
	    if (place.address_components) {
	      address = [
	        (place.address_components[0] && place.address_components[0].short_name || ''),
	        (place.address_components[1] && place.address_components[1].short_name || ''),
	        (place.address_components[2] && place.address_components[2].short_name || '')
	      ].join(' ');
	    }
	    fromInfowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
	    fromInfowindow.open(window.map, fromMarker);
	  });
	
	google.maps.event.addListener(toAutocomplete, 'place_changed', function() {
		toInfowindow.close();
	    toMarker.setVisible(false);
	    var place = toAutocomplete.getPlace();
	    if (!place.geometry) {
	      return;
	    }
	    // If the place has a geometry, then present it on a map.
	    if (place.geometry.viewport) {
	      window.map.fitBounds(place.geometry.viewport);
	    } else {
	      window.map.setCenter(place.geometry.location);
	      window.map.setZoom(17);  // Why 17? Because it looks good.
	    }
	    toMarker.setIcon(/** @type {google.maps.Icon} */({
	      url: place.icon,
	      size: new google.maps.Size(71, 71),
	      origin: new google.maps.Point(0, 0),
	      anchor: new google.maps.Point(17, 34),
	      scaledSize: new google.maps.Size(35, 35)
	    }));
	    latlng = place.geometry.location;
	    toAddrLat = latlng.lat();
	    toAddrLng = latlng.lng();
	    toMarker.setPosition(place.geometry.location);
	    toMarker.setVisible(true);
	    var address = '';
	    if (place.address_components) {
	      address = [
	        (place.address_components[0] && place.address_components[0].short_name || ''),
	        (place.address_components[1] && place.address_components[1].short_name || ''),
	        (place.address_components[2] && place.address_components[2].short_name || '')
	      ].join(' ');
	    }
	    toInfowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
	    toInfowindow.open(window.map, toMarker);
	  });
}


//---------------------------response----------------------------------------

window.initializeOtherElement = function(map) {
	
	// Use the driver's information and place it into html
	
	initializeDriverInfo();
	
	// initialize event handlers for the buttons
	
	initializeListener();
	
	//get driver's position from the variables imported by the server and create a marker there
	
	driverLatLng = new google.maps.LatLng(window.backResult.driverInfo.lat, window.backResult.driverInfo.lng);
	window.markerDriver = initializeMarker(driverLatLng, window.map);
	
	// Draw and find the directions between the passenger and driver
	
	initializeDirections();
	
	//find distance between passenger and driver

};

/* 
 * Create a marker on the specified map
 * returns the set marker
 */
function initializeMarker(latlng, map) {
	marker = new google.maps.Marker({
		map: map,
		visible: true,
		draggable: true,
		animation: google.maps.Animation.DROP,
		position: latlng
	});
	return marker;
}

/**
 * initialize driver info in $("driverInfo")
 */
function initializeDriverInfo() {
	$("#driphoto").attr("src",window.backResult.driverInfo.photo);
	$("#name").text("Your Driver: " + window.backResult.driverInfo.name);
	$("#credit").text("Credit: " + window.backResult.driverInfo.credit);
}

/**
 * initialize the variables required to display driving directions
 */
function initializeDirections(){
	directionsDisplay = new google.maps.DirectionsRenderer({
		suppressMarkers:true,
	});
	directionsDisplay.setMap(window.map);
	calcRoute();
}

/**
 * Call google to calculate the driver route and display the route
 */
function calcRoute(){
	directionsService = new google.maps.DirectionsService();
	var request={
		origin: driverLatLng,
		destination: window.passengerLatLng,
		travelMode:google.maps.TravelMode.DRIVING
	};

	directionsService.route(request, function(response, status){

		if(status==google.maps.DirectionsStatus.OK){

			directionsDisplay.setDirections(response);

		}
	});
}
/*
 * Attach event handlers to accept and refuse buttons 
 * 
 */
function initializeListener() {
	$('#acceptBtn').on('tap', function(){
		var invocationData = {
				adapter : 'stAdp',
				procedure : 'sendAcceptReq',
				parameters : [{'dri_id' : window.backResult.driverInfo.id, 'cus_id': window.customer.id}]
		};
		busy.show();
		WL.Client.invokeProcedure(invocationData, {
			onSuccess : acceptSuccess,
			onFailure : acceptFailure
		});
	});
	$('#refuseBtn').on('tap', function(){
		var invocationData = {
				adapter : 'stAdp',
				procedure : 'sendRefuseReq',
				parameters : [{'dri_id' : window.backResult.driverInfo.id, 'cus_id': window.customer.id}]
		};
		busy.show();
		WL.Client.invokeProcedure(invocationData, {
			onSuccess : refuseSuccess,
			onFailure : refuseFailure
		});
	});
}

function acceptSuccess(result) {
	busy.hide();
	
	// imports results into global window variables
	
	window.backResult=result.invocationResult;
	window.backResult.driverInfo=result.invocationResult.dri_info;
	window.backDriInfo.driverInfo.id = window.backResult.driverInfo.id;
	window.backDriInfo.driverInfo.lat = window.backResult.driverInfo.lat;
	window.backDriInfo.driverInfo.lng = window.backResult.driverInfo.lng;
	window.backResult.distance = result.invocationResult.distance;
	window.backResult.saveTime = result.invocationResult.saveTime;
	//window.page=2;
	//$.mobile.changePage("../view/real-time.html");
//	alert(JSON.stringify(window.backResult.driverInfo));
//	alert(window.backDriInfo.driverInfo.id);
	
	//starts up the real-time page
	realtime();	
}

function acceptFailure(result) {
	alert("error");
}

/**
 * if refused, it changes back to the customer's main page
 */
function refuseSuccess(result) {
	busy.hide();
	window.page=0;
	$.mobile.changePage("../view/customer-main.html");
}

function refuseFailure(result) {
	busy.hide();
	window.page=0;
	alert("fail");
	$.mobile.changePage("../view/customer-main.html");
}
//--------------------------------real-time-------------------------------------------------

function realtime(){
	$(".cusmain").removeClass("hidden");
	$(".response").addClass("hidden");
	
	switchPopup();
	
	setInitPosition();
	
	setTimeout(function() {
          realTimeMove();
    }, 1000);
	
//	$("#mapContainer").on('tap', function() {
//		driverWin.setContent("<p>distance:" + window.backDriInfo.distance + "</p><p>saveTime:" + window.backDriInfo.saveTime + "</p>");
//		driverWin.open(window.map, markerDriver);
//		setTimeout(function() {
//		      driverWin.close();
//		}, 2000);
//	});
}

function setInitPosition() {
//	alert("dri_id:" + window.backDriInfo.driverInfo.id + " cus_id:" + window.customer.id);
	var invocationData = {
			adapter : 'stAdp',
			procedure : 'getDriverRealTimePosition',
			parameters : [{'dri_id' : window.backDriInfo.driverInfo.id, 'cus_id' : window.customer.id}]
	};
	WL.Client.invokeProcedure(invocationData, {
		onSuccess : setInitPositionSuccess,
		onFailure : getPositionFailure
	});
}

function setInitPositionSuccess(result) {
	var myResult = result.invocationResult;
	var currentLat = myResult.dri_info.lat;
	var currentLng = myResult.dri_info.lng;
	window.backDriInfo.distance = myResult.distance;
	window.backDriInfo.saveTime = myResult.saveTime;
	driverLatLng = new google.maps.LatLng(currentLat, currentLng);
	window.markerDriver.setPosition(driverLatLng);
	
	driverWin = new google.maps.InfoWindow({
		maxWidth : 10,
	    content: "<p>distance:" + window.backDriInfo.distance + "</p><p>saveTime:" + window.backDriInfo.saveTime + "</p>"
	 }); 
	driverWin.open(window.map, window.markerDriver);
	setTimeout(function() {
	      driverWin.close();
	}, 2000);
}

function realTimeMove() {
	if(continueTrace) {	
		oldLatLng = driverLatLng;
		
		var invocationData = {
				adapter : 'stAdp',
				procedure : 'getDriverRealTimePosition',
				parameters : [{'dri_id' : window.backDriInfo.driverInfo.id, 'cus_id' : window.customer.id}]
		};
		WL.Client.invokeProcedure(invocationData, {
			onSuccess : getPositionSuccess,
			onFailure : getPositionFailure
		});
	} else {
		alert("cleartimeout");
		window.setTimeout(function(){
			switchLoading();
		}, 300000);
		clearTimeout(setTimeOutFunc);
	}
}

function getPositionSuccess(result) {
	var myResult = result.invocationResult;
	var currentLat = myResult.dri_info.lat;
	var currentLng = myResult.dri_info.lng;
	window.backResult.distance = myResult.distance;
	window.backResult.saveTime = myResult.saveTime;
	driverLatLng = new google.maps.LatLng(currentLat, currentLng);
	window.markerDriver.setPosition(driverLatLng);
//	alert("currentLat" + currentLat);
	var points = [oldLatLng, driverLatLng];
	var mypath = new google.maps.Polyline({
		path:points,
		strokeColor:"red",
		strokeOpacity: .4,
		strokeWeight: 5,
		map: map
	});
	// Calculate distance between passenger and driver
	var currentDistance = google.maps.geometry.spherical.computeDistanceBetween(window.passengerLatLng, driverLatLng);
	if(currentDistance < 50){
		continueTrace = false;
	}
	setTimeOutFunc = setTimeout("realTimeMove()", 1000);
}
/**
 * get driver position request fail 
 */
function getPositionFailure(result) {
	alert("fail");
	setTimeOutFunc = setTimeout("realTimeMove()", 1000);
}

//------------------------------------- record -----------------------------
var mymedia = null;
var recordSrc = "record.ogg";

/**
 * after tap the mic start record or stop record
 */
function controlRecord() {
	alert("control");
	var currentStatus = $('#microphoto').data('state');
	if (currentStatus == "stop") {
		startRecordAudio();
		$('#microphoto').data('state', "running");
	} else if (currentStatus == "running") {
		stopRecordAudio();
		$('#microphoto').data('state', "stop");
	}
}

function startRecordAudio() {
	alert("startRecord");
	if (mymedia == null) {
		var recAudioSuccess = function() {
//			alert("startRecordAudio():Audio new Success");
		};
		var recAudioError = function(err) {
//			alert("startRecordAudio():Audio Error: " + err);
		};
		var recAudioStatus = function(status) {
//			alert("startRecordAudio():Audio Status: " + Media.MEDIA_MSG[status]);
		};
		mymedia = new Media(recordSrc, recAudioSuccess, recAudioError,
				recAudioStatus);
	}
	mymedia.startRecord();
}

function stopRecordAudio() {
	mymedia.stopRecord();
	playRecord();
}

function playRecord() {
	var media1 = new Media(window.recordSrc, function() {
//		alert("playAudio():Audio new Success");
	}, function(err) {
//		alert("playAudio():Audio new Error: " + err);
	}, function(status) {
//		alert("playAudio():Audio Status: " + Media.MEDIA_MSG[status]);
	});
	alert("playRecord");
	media1.play();
//	var fileLocation = "/data/data/com.SmartTest7_17/files/www/default/record.ogg";
//	alert(fileLocation);
	cordova.exec(encodeSuccess, encodeFailure, "EncodeUtilPlugin", "encodeAudio", [recordSrc]);
	
}

function encodeSuccess(result) {
	alert("success:" + result);
	var cus_id = "1";
	var dri_id = "1";
	var invocationData = {
			adapter : 'stAdp',
			procedure : 'sendAudio',
			parameters : [{'cus_id': cus_id,'dri_id':dri_id,'encodedString':result}]
	};
	WL.Client.invokeProcedure(invocationData, {
		onSuccess : receiveEncodeAudio,
		onFailure : decodeFailure
	});
}

function receiveEncodeAudio(result) {
	//alert(result.encodedString);
	var encodedContent = result.invocationResult.encodedString;
	cordova.exec(decodeSuccess, decodeFailure, "EncodeUtilPlugin", "decodeAudio", [encodedContent]);
}

function encodeFailure(result) {
	alert("fail:" + result);
}

function decodeSuccess(result) {
	alert("decodeSuccess");
}

function decodeFailure(result) {
	alert("decodeFail:");
}
//--------------------------------------------voice-----------------------
$("#microphoto").on('mouseover',function(){
	//alert("mouseover");
	$("#voicecontainer").removeClass("hidden");
	
});
$("#voicecontainer").on('mouseover',function(){
	//alert("mouseover");
	$("#voicecontainer").removeClass("hidden");
	
});
$("#voicecontainer").on("mouseout",function(){
	//alert("mouseout");
	$("#voicecontainer").addClass("hidden");
});
